package com.book.kafka.client.config;

import com.book.kafka.client.exception.KafkaConsumerException;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.record.CompressionType;
import org.apache.kafka.streams.StreamsConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.listener.AbstractMessageListenerContainer;
import org.springframework.kafka.listener.ConsumerAwareListenerErrorHandler;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.MessageHeaders;

import java.util.HashMap;
import java.util.Map;

/**
 * Kafka config
 * Created by IT on 2017/3/29.
 */
@Configuration
@EnableKafka
@PropertySource("classpath:kafka.properties")
public class KafkaConfig {

    public KafkaConfig() {
//        if (System.getProperty("java.security.auth.login.config") == null) {
//            System.setProperty("java.security.auth.login.config", KAFKA_CLIENT_JAAS);
//        }
    }

    private final static String STRING_SERIALIZER_CLASS = "org.apache.kafka.common.serialization.StringSerializer";
    private final static String STRING_DESERIALIZER_CLASS = "org.apache.kafka.common.serialization.StringDeserializer";
    private final static String BYTE_ARRAY_SERIALIZER_CLASS = "org.apache.kafka.common.serialization.ByteArraySerializer";
    private final static String BYTE_ARRAY_DESERIALIZER_CLASS = "org.apache.kafka.common.serialization.ByteArrayDeserializer";

    @Value("${bootstrap.servers}")
    private String bootstrapServers;

    @Value("${group.id}")
    private String groupId;

    @Value("${stream.app.id}")
    private String streamAppId;

    @Value("${enable.ssl:false}")
    private Boolean enableSsl;

    @Value("${max.poll.records.size:20}")
    private String maxPollRecordsSize;

    @Value("${linger.ms:1}")
    private Integer lingerMs;
    @Value("${batch.size:16384}")
    private Integer batchSize;

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "60000");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, STRING_DESERIALIZER_CLASS);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BYTE_ARRAY_DESERIALIZER_CLASS);
        return props;
    }

    @Bean
    public Map<String, Object> batchConsumerConfig() {
        Map<String, Object> props = this.consumerConfigs();
        // 手动提交
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecordsSize);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return props;
    }

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.RETRIES_CONFIG, 3);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, CompressionType.SNAPPY.name);
        props.put(ProducerConfig.LINGER_MS_CONFIG, lingerMs);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER_CLASS);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, BYTE_ARRAY_SERIALIZER_CLASS);
        return props;
    }

    @Bean
    public Map<String, Object> streamConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, streamAppId);
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        return props;
    }

    @Bean
    public ProducerFactory<String, byte[]> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }


    @Bean
    public ConsumerFactory<String, byte[]> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public ConsumerFactory<String, byte[]> batchConsumerFactory() {
        return new DefaultKafkaConsumerFactory<>(batchConsumerConfig());
    }

    @Bean
    public StreamsConfig streamConfig() {
        return new StreamsConfig(streamConfigs());
    }

    @Bean
    public KafkaTemplate<String, byte[]> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, byte[]> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, byte[]> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    @Bean("batchKafkaListenerContainerFactory")
    public ConcurrentKafkaListenerContainerFactory<String, byte[]> batchKafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, byte[]> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(batchConsumerFactory());
        //设置批量
        factory.setBatchListener(true);
        //设置提交偏移量的方式
        factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.MANUAL_IMMEDIATE);
        return factory;
    }

    @Bean("consumerAwareErrorHandler")
    public ConsumerAwareListenerErrorHandler consumerAwareErrorHandler() {
        return (message, error, consumer) -> {
            MessageHeaders headers = message.getHeaders();
            Throwable cause = error.getCause();
            if (cause instanceof KafkaConsumerException) {
                int offsetChange = -1;
                switch (((KafkaConsumerException) cause).getType()) {
                    case KafkaConsumerException.IGNORE:
                        offsetChange = -1;
                        break;
                    case KafkaConsumerException.CONTINUE_RESTRICT:
                        offsetChange = 0;
                        break;
                    case KafkaConsumerException.CONTINUE_JUMP:
                        //offsetChange = 1;
                        break;
                }
                if (offsetChange > -1) {
                    consumer.seek(new org.apache.kafka.common.TopicPartition(
                                    headers.get(KafkaHeaders.RECEIVED_TOPIC, String.class),
                                    headers.get(KafkaHeaders.RECEIVED_PARTITION_ID, Integer.class)),
                            headers.get(KafkaHeaders.OFFSET, Long.class) + offsetChange);
                }
            }
            return null;
        };
    }

}
